package demo;

public class ThreadLocalExample {

    private static final ThreadLocal<Integer> threadLocalCounter = ThreadLocal.withInitial(()->0);

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new Thread(new CounterTask(i)).start();
        }
    }

    private static class CounterTask implements Runnable {

        private final int threadId;
        public CounterTask(int threadId) {
            this.threadId = threadId;
        }

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                int counter = threadLocalCounter.get();
                threadLocalCounter.set(counter + 1);
                System.out.println("thread:"+threadId+";counter : "+threadLocalCounter.get());

            }
        }
    }



}
